#include <stdio.h>
#include <string.h>
#include <arpa/inet.h> // 注意：在某些系统上可能是 <netinet/in.h>，但 <arpa/inet.h> 通常包含了它
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h> // 包含 exit 和 EXIT_FAILURE 的定义
 
#define PORT 8080
#define BROADCAST_IP "255.255.255.255"
#define BUFFER_SIZE 1024
 
int main() {
    int sockfd;
    struct sockaddr_in broadcastAddr;
    const char *message = "Hello, this is a broadcast message!";
    char buffer[BUFFER_SIZE];
 
    // 创建 UDP 套接字
    if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
        perror("socket creation failed");
        exit(EXIT_FAILURE);
    }
 
    int broadcastEnable = 1;
    // 启用广播选项
    if (setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &broadcastEnable, sizeof(broadcastEnable)) < 0) {
        perror("setsockopt(SO_BROADCAST) failed");
        close(sockfd);
        exit(EXIT_FAILURE);
    }
 
    // 设置广播地址和端口
    memset(&broadcastAddr, 0, sizeof(broadcastAddr));
    broadcastAddr.sin_family = AF_INET;
    broadcastAddr.sin_addr.s_addr = inet_addr(BROADCAST_IP);
    broadcastAddr.sin_port = htons(PORT);
 
    // 发送广播消息
    if (sendto(sockfd, message, strlen(message), MSG_CONFIRM, (const struct sockaddr*)&broadcastAddr, sizeof(broadcastAddr)) < 0) {
        perror("sendto failed");
        close(sockfd);
        exit(EXIT_FAILURE);
    }
 
    printf("Broadcast message sent: %s\n", message);
 
    // 关闭套接字
    close(sockfd);
 
    return 0;
}